import json
from langchain import LLMChain, PromptTemplate
from langchain.llms import OpenAI
from langchain.chains import SimpleSequentialChain
from langchain.memory import ConversationBufferMemory
from langchain.prompts import ChatPromptTemplate
from langchain.chat_models import ChatOpenAI
import os
from openai import OpenAI
from dotenv import load_dotenv

# 加载知识库
def load_intents(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        intents = json.load(file)
    return intents

# 初始化大模型
load_dotenv()  # 加载 .env 文件
client = OpenAI(
    # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

# 定义意图识别的模板
intent_template = """
You are an intent recognition system. Given the user's input, classify it into one of the following categories:
1. 日常对话
2. 新客户发展场景
3. 存量客户运营场景
4. 客户高价值经营场景
5. 混合场景

User Input: {user_input}
Intent: 
"""

# 定义意图识别链
llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.7)
intent_chain = LLMChain(
    llm=llm,
    prompt=ChatPromptTemplate.from_template(intent_template),
    output_key="intent"
)

# 定义响应生成的模板
response_template = """
You are a helpful assistant. Given the user's input and the identified intent, generate an appropriate response.

User Input: {user_input}
Intent: {intent}
Response: 
"""

# 定义响应生成链
response_chain = LLMChain(
    llm=llm,
    prompt=ChatPromptTemplate.from_template(response_template),
    output_key="response"
)

# 定义整体流程
overall_chain = SimpleSequentialChain(chains=[intent_chain, response_chain], verbose=True)

# 加载知识库
intents = load_intents('intents.json')

# 定义知识库查询函数
def query_knowledge_base(intent, user_input):
    for intent_data in intents['intents']:
        if intent_data['tag'] == intent:
            for pattern in intent_data['patterns']:
                if pattern in user_input:
                    return f"匹配到的知识库条目: {pattern}"
    return "未找到相关知识库条目"

# 主逻辑
def main(user_input):
    # 识别意图
    intent_result = intent_chain({"user_input": user_input})
    intent = intent_result["intent"].strip()

    # 查询知识库
    knowledge_base_response = query_knowledge_base(intent, user_input)

    # 生成响应
    response_result = response_chain({"user_input": user_input, "intent": intent})
    response = response_result["response"].strip()

    # 打印结果
    print(f"User Input: {user_input}")
    print(f"Identified Intent: {intent}")
    print(f"Knowledge Base Response: {knowledge_base_response}")
    print(f"Generated Response: {response}")

# 测试
if __name__ == "__main__":
    user_input = "北京家庭圈中有多少异网用户"
    main(user_input)
